<?php

class Storage
{
	private static $_config = null;

	/**
	 * get instance of storage service
	 * @param string $name
	 * @return Storage_Adapter
	 */
	static public function instance($id = NULL)
	{
		static $instances = array();

		if (null == $id)
		{
			$id = self::getDefaultId();
		}

		if (!isset($instances[$id]))
		{
			$config = self::getConfig($id);
			$service = $config['service_id'];
			$class = 'Storage_Adapter_' . ucfirst($service);
			$instances[$id] = new $class($id, $config);
		}
		return $instances[$id];
	}

	static public function getDefaultId()
	{
		static $id = NULL;

		if (null == $id)
		{
			$key = 'core/storage/default';
			$id = Cache::instance() -> get($key);
			if (null == $id)
			{
				$id = Model::getTable('core/storage') -> getDefaultId();
				Cache::instance() -> set($key, $id);
			}
		}
		return $id;
	}

	/**
	 * get configure of storage service
	 * @param string $name
	 * @return array
	 *
	 */
	static public function getConfig($id)
	{
		static $config = null;

		if (!isset($config[$id]))
		{
			$config[$id] = Config::instance('core/storage') -> get($id);
		}

		if (false == $config[$id])
		{
			throw new Agilet_Exception('Could not find storage configure for service {serivce}', array('{service}' => $id));
		}
		return $config[$id];
	}

}
